package com.woniuxy.dudugua.controller;

import com.woniuxy.dudugua.entity.Address;
import com.woniuxy.dudugua.entity.User;
import com.woniuxy.dudugua.exception.IncorrectCredentialsException;
import com.woniuxy.dudugua.service.AddressService;
import com.woniuxy.dudugua.service.OrderService;
import com.woniuxy.dudugua.service.UserService;
import com.woniuxy.dudugua.util.Result;
import com.woniuxy.dudugua.util.message.SendMessage;
import com.woniuxy.dudugua.util.qnyutil.QiniuUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 用户控制层
 */
@RestController
@Slf4j
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @Resource
    private AddressService addressService;
    @Resource
    private QiniuUtil qiniuUtil;
    @Resource
    private OrderService orderService;
    /**
     * 用户登录的方法
     */
    @GetMapping("login")
    public Result loginByTel(String mobile,String password) throws Exception {
        //封装用户名和密码
        UsernamePasswordToken token = new UsernamePasswordToken(mobile,password);
        //创建subject实例
        Subject subject = SecurityUtils.getSubject();
        //判断当前subject是否登录
        if(subject.isAuthenticated()==false){
            //执行登录认证
            subject.login(token);
        }
        User user = (User) subject.getPrincipal();
        return new Result("200","登录成功",user,null);
    }
    /**
     * 用户注册
     */
    @PostMapping("register")
    public Result register(@RequestBody User user)throws Exception{
        user.setMoney(BigDecimal.valueOf(5000));
        userService.register(user);
        return new Result("200","success",null,null);
    }
    /**
     * 短信验证
     */
    @RequestMapping("checkCode")
    public Result checkCode(String tel)throws Exception{
        //随机生成4位验证码
        String code="";
        for(int i=0;i<4;i++){
            code+=new Random().nextInt(10);
        }
        System.out.println(code);
        SendMessage.sendMessage(code,tel);
        return new Result("200","success",code,null);
    }
    /**
     * 修改个人资料
     */
    @PutMapping("update")
    public Result updateUser(@RequestBody User userInfo)throws Exception{
        userService.updateUser(userInfo);
        return new Result("200","success",null,null);
    }
    /**
     * 查询用户地址
     */
    @GetMapping("address")
    public Result getAddress()throws Exception{
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Integer userId = user.getId();
        List<Address> addresses = userService.selectAddressByUserId(userId);
        return new Result("200","success",null,addresses);
    }
    /**
     * 传过来一个地址对象，更新
     */
    @PostMapping("updateAddress")
    public Result updateAddress(@RequestBody Address addressView)throws Exception{
        addressService.updateAddress(addressView);
        return new Result("200","success",null,null);
    }
    /**
     * 穿过来一个地址对象，添加
     */
    @PostMapping("addAddress")
    public Result insertAddress(@RequestBody Address addressView)throws Exception{
        addressService.insertAddress(addressView);
        return new Result("200","success",null,null);
    }
    /**
     * 查询用户信息
     */
    @GetMapping("selectInfo")
    public Result selectInfo()throws Exception{
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        log.info("查询用户信息");
        return new Result("200","success",userService.selectInfo(user.getId()),orderService.selectAllConpons(user.getId()));
    }
    /**
     * 用户查看评论
     */
    @GetMapping("selectComment")
    public Result selectComment() throws Exception{
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Integer userId=user.getId();
        return new Result("200","success",null,userService.selectComment(userId));
    }

    /**
     * 用户更换头像
     * @param image
     * @return
     * @throws IOException
     */
    @RequestMapping("changehead")
    public Result updateHead(@RequestParam("image")MultipartFile image) throws IOException {
        String fileName = "headPortrait/"+ UUID.randomUUID().toString();
        qiniuUtil.upload(fileName,image.getInputStream());
        String s = qiniuUtil.fullPath(fileName);
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        user.setUrl(s);
        userService.updateHead(user);
        return new Result("200","success",null,null);
    }
}
